package com.axjy.web;

import com.axjy.pojo.Logs;
import com.axjy.pojo.User;
import com.axjy.service.LogsService;
import com.axjy.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by asus on 2018/2/3.
 */
@Controller
@RequestMapping("/sys")
public class LoginHandler {

    @Resource
    private UserService userService;

    @Resource
    private LogsService logsService;

    @PostMapping("/login")
    public String login(String userCode, String userPassword, HttpSession session,Logs logs){
        User user=userService.Login(userCode, userPassword);
        if(user==null){
            throw  new RuntimeException("用户名或密码错误！");
        }
        session.setAttribute("loginUser",user);

        logs.setOperateinfo("用户登录");
        logs.setUsercode(user.getUserCode());
        logs.setUsername(user.getUserName());
        logsService.addLogs(logs);
        return "redirect:/index";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session,Logs logs){
        User userCode = (User) session.getAttribute("loginUser");
        logs.setOperateinfo("用户退出");
        logs.setUsercode(userCode.getUserCode());
        logs.setUsername(userCode.getUserName());
        logsService.addLogs(logs);
        userService.updatLoginTime(userCode.getUserCode());
        session.invalidate();
        return "redirect:/login.jsp";
    }
}
